//
//  CNStatusDAL.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/4/8.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit
// 加载数据
class CNStatusDAL: NSObject {
    static let sharedDAL = CNStatusDAL()
    private override init() {
        super.init()
    }
    private let cacheDataTime: NSTimeInterval = 60
    func clearData() {
        let overDate = NSDate(timeIntervalSinceNow: -cacheDataTime)
        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "EN")
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let ovetTime = formatter.stringFromDate(overDate)
        let sql = "DELETE FROM T_status WHERE createTime < '\(ovetTime)';"
        CNSQLiteManager.sharedManager.dbQueue.inDatabase { (db) -> Void in
            do {
                try db.executeUpdate(sql, values: [])
            } catch let error as NSError {
                CNPrint(item: "清楚缓存失败: \(error)")
            }
        }
    }
    /// 加载数据
    func dalLoadStatus(since_id: Int64, max_id: Int64, dalLoadStatusCallback: (statuses: [[String: AnyObject]]?, error: NSError?) -> ()) {
        // 1.本地加载数据
        loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            if statuses != nil && statuses?.count > 0 {
                // 2.本地加载到数据,返回
                dalLoadStatusCallback(statuses: statuses, error: nil)
                return
            }
            // 3.本地没有数据,使用网络工具类加载数据
            let urlString = "2/statuses/home_timeline.json"
            var parameters = [String: AnyObject]()
            // 每次加载10条数据
            parameters["count"] = 10
            if since_id > 0 { // 需要下拉刷新
                parameters["since_id"] = NSNumber(longLong: since_id)
            } else if max_id > 0 { // 需要上拉加载更多
                parameters["max_id"] = NSNumber(longLong: max_id - 1)
            }
            CNNetworkTool.sharedInstance.sendGetRequest(urlString, parameters: parameters) { (result, error) -> () in
                if error != nil {
                    CNPrint(item: "请求网络数据失败: \(error)")
                    dalLoadStatusCallback(statuses: nil, error: error)
                    return
                }
                // 4.将加载到的网络数据保存到本地
                let data = result?["statuses"] as? [[String: AnyObject]]
                if data != nil {
                    self.saveStatus(data!)
                    // 5.将网络数据返回
                    dalLoadStatusCallback(statuses: data, error: nil)
                } else {
                    dalLoadStatusCallback(statuses: nil, error: nil)
                }
            }
        }
    }
    /// 从本地数据库读取微博数据
    private func loadStatus(since_id: Int64, max_id: Int64, loadCacheFinish: (statuses: [[String: AnyObject]]?, error: NSError?) -> ()) {
        let userId = CNUserAccountViewModel.sharedInstance.userAccount?.uid
        assert(userId != nil, "uid为空")
        var sql = "SELECT status FROM T_status "
        if since_id > 0 {
            sql += "WHERE statusId > \(since_id) AND userId = \(Int(userId!)!) "
        } else if max_id > 0 {
            sql += "WHERE statusId < \(max_id) AND userId = \(Int(userId!)!) "
        } else {
            sql += "WHERE userId = \(Int(userId!)!) "
        }
        sql += "ORDER BY statusId DESC LIMIT 20"
//        CNPrint(item: "sql: \(sql)")
        CNSQLiteManager.sharedManager.dbQueue.inDatabase { (db) -> Void in
            do {
                let result = try db.executeQuery(sql, values: [])
                var statuses = [[String: AnyObject]]()
                while result.next() {
                    let string = result.stringForColumn("status")
                    let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
                    let dict = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as! [String: AnyObject]
                    statuses.append(dict)
                }
                loadCacheFinish(statuses: statuses, error: nil)
            } catch let error as NSError {
                CNPrint(item: "从数据库加载数据失败: \(error)")
                loadCacheFinish(statuses: nil, error: error)
            }
        }
    }
    /// 保存微博数据到本地数据库
    private func saveStatus(statuses: [[String: AnyObject]]) {
        let userId = CNUserAccountViewModel.sharedInstance.userAccount?.uid
        assert(userId != nil, "uid为空")
        let sql = "INSERT INTO T_Status (statusId, status, userId) VALUES (?, ?, ?)"
        CNSQLiteManager.sharedManager.dbQueue.inTransaction { (db, _) -> Void in
            do {
                for dict in statuses {
                    let statusId = dict["id"] as! Int
                    let data = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
                    let status = String(data: data, encoding: NSUTF8StringEncoding)!
                    try db.executeUpdate(sql, values: [statusId, status, Int(userId!)!])
                }
            } catch let error as NSError {
                CNPrint(item: "保存微博数据失败: \(error)")
            }
            
        }
    }
}
